﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using LynxWebLog.ViewModels;

namespace LynxWebLog.Controllers
{
    public class CKEditorController : Controller
    {
        //
        // GET: /CKEditor/
        [Authorize(Roles="BlogUser,BlogAdmin")]
        public async Task<ActionResult> BrowseImage(string CKEditorFuncNum, string CKEditor, string langCode)
        {
            HttpClient client = ClientUtility.BlogAPIClient();
            BrowseImageView biv = new BrowseImageView() { CKEditorFuncNum = CKEditorFuncNum };

            HttpResponseMessage resp = await client.GetAsync("api/MediaObjectData/?$filter=username eq '" + User.Identity.Name + "'");
            resp.EnsureSuccessStatusCode();
            IEnumerable<MediaObjectData> mod = await resp.Content.ReadAsAsync<IEnumerable<MediaObjectData>>();
            List<string> tPath = new List<string>();
            foreach (MediaObjectData item in mod) {
                tPath.Add("http://WinRc8_1/LynxWebLog/Blogs/" + User.Identity.Name + "/MediaAccess/Media/GetImage/?imgName=" + item.name);
            }
            biv.ImagePaths = tPath.AsEnumerable();

            return View("BrowseImage", biv);
        }

        [HttpPost, Authorize(Roles="BlogUser,BlogAdmin")]
        public async  Task<ActionResult> UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            string vOutput = string.Empty;
            string vMessage = string.Empty;
            MediaObject mobj = new MediaObject();

            try {
                mobj.name = upload.FileName;
                mobj.type = upload.ContentType;
                BinaryReader r = new BinaryReader(upload.InputStream);
                mobj.bits = r.ReadBytes((int)upload.InputStream.Length);

                MediaObjectInfo moi = await BlogRoot.MwlAPI.NewMediaObject(User.Identity.Name, string.Empty, mobj);
                vMessage = "MediaObject saved correctly";
            }
            catch {
                vMessage = "There was an issue uploading the MediaObject";
            }
            vOutput = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",\"/MediaAccess/Media/GetImage/?imgName=" + upload.FileName + "\", \"" + vMessage + "\");</script></body></html>";
            return Content(vOutput);
        }
	}
}